<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="title">修改密码</span>
      </div>
      <el-form class="form" :model="form" ref="form" label-position="top">
        <el-form-item label="旧密码">
          <el-input v-model="form.oldPassword" clearable maxlength="20" placeholder="原始密码,长度20字以内"/>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="form.password" clearable type="password"  maxlength="20" placeholder="设置新密码,长度20字以内"/>
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input v-model="form.password2" clearable type="password"  maxlength="20" placeholder="确认新密码,长度20字以内"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirms">确认</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { isvalidUsername } from '@/utils/validate'
// import { updatePassword } from '@/api/user'
import Cookies from 'js-cookie'

export default {
  name: 'change-password',
  data() {
    return {
      form: {
        oldPassword: '',
        password: '',
        password2: ''
      },
      rules: {}
    }
  },
  methods: {
    goBack() {
      window.history.back()
    },
    async confirms() {
      if (!isvalidUsername(this.form.oldPassword)) {
        this.$message.error('旧密码不能为空')
        return
      }
      if (this.form.oldPassword.length < 5) {
        this.$message.error('旧密码至少6位')
        return
      }
      if (!isvalidUsername(this.form.password)) {
        this.$message.error('新密码不能为空')
        return
      }
      if (this.form.password.length < 5) {
        this.$message.error('新密码至少6位')
        return
      }
      if (this.form.password != this.form.password2) {
        this.$message.error('两次密码输入不一致')
        return
      }
      const searchOptions = {
        newPassword: this.form.password || '',
        oldPass: this.form.oldPassword || '',
        comPass: this.form.password2 || ''
      }
      const { success } = await updatePassword(searchOptions)
      if (success) {
        this.$message({
          message: '修改密码成功',
          type: 'success'
        })
        // this.$router.go(-1)
        this.$store.dispatch('LogOut').then(() => {
          location.reload()// In order to re-instantiate the vue-router object to avoid bugs
        })
      } else {
        this.$message.error('修改密码失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f0f2f5;
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
.form {
  width: 360px;
}
</style>
